﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Caching;
using System.Xml.Linq;

namespace MPic.Utility
{
    public class RedisConfigHelper
    {

        /// <summary>
        /// 可写的Redis链接地址
        /// </summary>
        public static string WriteServerList
        {
            get { return GetValueFromXML("WriteServerList"); }
        }

        /// <summary>
        /// 可读的Redis链接地址
        /// </summary>
        public static string ReadServerList
        {
            get { return GetValueFromXML("ReadServerList"); }
        }

        /// <summary>
        /// 最大写链接数
        /// </summary>
        public static string MaxWritePoolSize
        {
            get { return GetValueFromXML("MaxWritePoolSize"); }
        }

        /// <summary>
        /// 最大读链接数
        /// </summary>
        public static string MaxReadPoolSize
        {
            get { return GetValueFromXML("MaxReadPoolSize"); }
        }

        /// <summary>
        /// 自动重启
        /// </summary>
        public static string AutoStart
        {
            get { return GetValueFromXML("AutoStart"); }
        }

        /// <summary>
        /// 是否记录日志,该设置仅用于排查redis运行时出现的问题,如redis工作正常,请关闭该项
        /// </summary>
        public static string RecordeLog
        {
            get { return GetValueFromXML("RecordeLog"); }
        }

        /// <summary>
        /// 本地缓存到期时间，单位:秒
        /// </summary>
        public static string LocalCacheTime
        {
            get { return GetValueFromXML("LocalCacheTime"); }
        }


        //读取站点Redis
        private static string GetValueFromXML(string elementName)
        {
            string result = string.Empty;
            try
            {
                string filepath = AppDomain.CurrentDomain.BaseDirectory + @"/Config/Redis.config";
                CacheDependency fileDependency = new CacheDependency(filepath);
                var cache = DataCache.GetCache("SystemParam_ConfigFile_" + elementName);
                if (cache == null)
                {
                    XElement xml = XElement.Load(filepath);
                    result = xml.Element(elementName).Value;
                    DataCache.SetCache("SystemParam_ConfigFile_" + elementName, result, fileDependency);
                }
                else
                {
                    result = cache.ToString();
                }
            }
            catch (Exception e)
            {
                LoggerHelper.Log("【SystemParameterHelper】->【GetValueFromXML】：" + e.Message);
            }
            return result;
        }
    }
}
